package service

import (
	"file_sys_server/model"
	"file_sys_server/serializer"
	"file_sys_server/utils"

	"gorm.io/gorm"
)

type SampleService struct {
	// gorm.Model
	ID            int64   `gorm:"column:id"`             // 样品id
	SampleCode    string  `gorm:"column:sampleCode"`     // 样品编号
	SampleName    string  `gorm:"column:sampleName"`     // 样品名称
	RelateProject string  `gorm:"column:relatedProject"` // 所属项目
	Limit         string  `gorm:"column:limit"`          // 灵敏度 检测限值
	PreI1         uint    `gorm:"column:preI1"`          //预留字段
	PreF1         float32 `gorm:"column:preF1"`          //预留字段
	PreStr1       string  `gorm:"column:preStr1"`        //预留字段
}

// 读取本地Excel数据存储到mysql数据库
func AddRecordsFromLocal() serializer.Response {
	records, err := utils.ConvertSampleToBean() // 直接读本地值
	if err != nil {
		return serializer.Response{
			Code: 10003,
			Msg:  err.Error(),
		}
	}

	err = insertOrReplaceSample(model.DB, records)

	if err != nil {
		return serializer.Response{
			Code: 10003,
			Msg:  err.Error(),
		}
	}

	return serializer.Response{
		Code: 10000,
		Msg:  "success",
	}
}

// 新增插入样品
func insertOrReplaceSample(db *gorm.DB, samples []*model.Sample_bean_mfdcg) error {
	for _, sample := range samples {
		var oldSample model.Sample_bean_mfdcg

		err := db.Where("sampleCode=?", sample.SampleCode).FirstOrCreate(&oldSample).Error
		if err != nil {
			return err
		}
		if oldSample.ID == 0 {
			if err := db.Create(sample).Error; err != nil {
				return err
			}
		} else {
			sample.ID = oldSample.ID

			if err := db.Save(sample).Error; err != nil {
				return err
			}
		}
	}
	return nil
}

// 获取样品列表数据
func GetSampleList() serializer.Response {
	var samples []*model.Sample_bean_mfdcg
	err := model.DB.Find(&samples).Error

	if err != nil {
		return serializer.Response{
			Code: 10003,
			Msg:  err.Error(),
		}
	}

	return serializer.Response{
		Code: 10000,
		Msg:  "success",
		Data: serializer.BuildSamples(samples),
	}
}
